package likou.tanxin;

import java.util.Arrays;

/**
 * @author: Tangxz
 * @email: 1171702529@qq.com
 * @cate: 2020/11/09 17:57
 */
public class _910 {
    public static void main(String[] args) {
        System.out.println(smallestRangeII(new int[]{7,8,8},5));
    }

    public static int smallestRangeII(int[] A, int K) {
        if(A.length==1){
            return 0;
        }else if(A.length==2){
            if(A[1]-K>=A[0]+K){
                return A[1]-A[0]-2*K;
            }else{
                return Math.min(A[1]-A[0],A[0]-A[1]+2*K);
            }
        }
        Arrays.sort(A);
        K=Math.abs(K);
        int index1=0,index2=0;
        int num=A[0]+2*K;
        for(int i=0;i<A.length;i++){
            if(num>=A[i]){
                index1=i;
            }
        }
        num=A[A.length-1]-2*K;
        for(int i=A.length-1;i>=0;i--){
            if(num<=A[i]){
                index2=i;
            }
        }
        int ans=A[A.length-1]-A[0];
        if(index1<index2){
            return A[A.length-1]-A[0]-2*K;
        }else if(index1==index2||index1-index2==1){
            return Math.min(A[A.length-1]-A[index1],A[index1]-A[0]);
        }else{
            ans=Math.min(A[A.length-1]-A[index2],A[index1]-A[0]);
            for(int i=index2;i<index1;i++){
                ans=Math.min(ans,A[i]-A[i+1]+2*K);
            }
            return ans;
        }
    }

}
